package org.lisy.designpattern.memento;

/**
 * 备忘录模式
 * - 发起人(Originator)
 * - 备忘录(Memento)
 * - 管理者(Caretaker)
 * 优缺点:
 * - 优点:提供了一种可以恢复状态的机制，实现了内部状态的封装，简化了发起人类单一职责
 * - 缺点:资源消耗大
 * 
 * @author lisy
 */
public class MementoMain {

	public static void main(String[] args) {
		
		Originator originator = new Originator();
		Caretaker caretaker = new Caretaker();
		beforeState(caretaker, originator);
		nextState(caretaker, originator);
		
		// 更新状态并记录
		operateState(caretaker, originator, "0", "initial");
		operateState(caretaker, originator, "1", "new");
		operateState(caretaker, originator, "2", "new");
		operateState(caretaker, originator, "3", "new");
		
		// 上一步
		beforeState(caretaker, originator);
		beforeState(caretaker, originator);
		beforeState(caretaker, originator);
		beforeState(caretaker, originator);
		
		// 下一步
		nextState(caretaker, originator);
		nextState(caretaker, originator);
		nextState(caretaker, originator);
		nextState(caretaker, originator);
	}

	private static void operateState(Caretaker caretaker, Originator originator, String state, String log) {
		originator.setState(state);
		caretaker.setMemento(originator.createMemento());
        System.out.println(log + " record state " + originator.getState());
	}

	private static void beforeState(Caretaker caretaker, Originator originator) {
		originator.restoreMemento(caretaker.getMemento()); 
        System.out.println("resume state " + originator.getState());
	}
	
	private static void nextState(Caretaker caretaker, Originator originator) {
		originator.restoreMemento(caretaker.getNextMemento()); 
        System.out.println("next state " + originator.getState());
	}

}
